package view;
import java.net.* ;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.* ;

import clientRequest.ClientRequest;
/**
 * 
 * @author user
 *
 */
public class SocketServer implements Runnable{
	private int maxOfExecutors=10; 
	private ExecutorService clientRequestPool= Executors.newFixedThreadPool(maxOfExecutors);
	boolean finish=false;

	
	public SocketServer() {
	}
	
	/**
	 * 
	 */
	public void run () {
	    ServerSocket serverSocket=null;
	    PrintWriter out = null;
	    ObjectInputStream in = null;
	    //BufferedReader stringIn = null;
	    
	    try { 
	    	serverSocket = new ServerSocket(4444);
	    	System.out.println("Server started");
	    }
	    catch (IOException e) { 
	    	System.err.println("Cannot listen on port 4444");
	    	System.exit(-1);
	    }
	    
	    Socket clientSocket=null;
	    while(!finish){
		    try { 
		    	System.out.println("accept client socket");
		    	clientSocket=serverSocket.accept();
		    	System.out.println("accepted client socket");
		    	System.out.println("1");
		    	out=new PrintWriter(clientSocket.getOutputStream(),true);
		    	System.out.println("2");
		    	InputStream is = clientSocket.getInputStream();
		    	System.out.println("2a");
		    	in= new ObjectInputStream(is); //
		    	
		    	//stringIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		    
		    	System.out.println("3");
		    	/*try {
		    		System.out.println("4");
					ClientRequest clientRequest = (ClientRequest) in.readObject();
					clientRequest.printRequest();
					System.out.println("5");
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					System.out.println("object failed");
					e.printStackTrace();
				}*/
		    	//for free this thread to listen to another requests
		    	clientRequestPool.execute(new MyProtocol(in,out,clientSocket));
		    }
		    catch (IOException e) {
		    	System.err.println("Accept failed");
		    	e.printStackTrace();
		    	//System.exit(-1);
		    }
	    }	
	    
		try {
			if (serverSocket!=null)
				serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  }
	
	void setFinish (){
		finish=true;
	}
}
